<?php
namespace app\common\service\util;

/**
 * gitcode服务
 */
class GitCode
{
    /**
     * 项目根目录
     */
    protected $dir; 
    public function __construct()
    {
        $this->dir = ROOT_PATH;
    }

    /**
     * 拉取标签
     */
    public function fetch()
    {
        chdir($this->dir);
        exec('git pull 2>&1', $fetchOutput, $fetchCode);
        // exec('git fetch --tag 2>&1', $fetchOutput, $fetchCode);
        if($fetchCode !== 0){
            return ['code' => 0, 'msg' => 'pull失败: ' . implode("\n", $fetchOutput)];
        }
        exec('git tag -l 2>&1', $tags, $tagCode);
        if($tagCode !== 0){
            return ['code' => 0, 'msg' => '获取tag失败: ' . implode("\n", $tags)];
        }
        return array_filter($tags);
    }

    /**
     * 切换标签
     */
    public function checkout($tagName)
    {
        chdir($this->dir);
        exec('git switch ' .  escapeshellarg($tagName) . ' 2>&1', $output, $returnCode);
        // exec('git checkout tags/' .  escapeshellarg($tagName) . ' 2>&1', $output, $returnCode);
        if ($returnCode !== 0) {
            return ['code' => 0, 'msg' => '切换标签失败: ' . implode(" ", $output)];
        }

        return ['code' => 1, 'msg' => '切换标签成功: ' . implode(" ", $output)];
    }
}